package com.itheima.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;


@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
        private SetmealService setmealService;

    @Autowired
        private JedisPool jedisPool;

    //1.新建套餐
    @RequestMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal){
        setmealService.add(setmeal);
       // 把所有上传的图片放到     第二个集合中     点击保存的
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        return Result.success(MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    //2. 分页
    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
         return setmealService.findPage(queryPageBean);
    }


    //3. 上传图片
    @RequestMapping("/upload.do")
    public Result upload(MultipartFile imgFile){
        try {
            //1. 修改图片名称
                    //1.0 获取原文件的名字
                            String originalFilename = imgFile.getOriginalFilename();

                    //1.1 找到最后一个点的位置
                            int index = originalFilename.lastIndexOf(".");

                    //1.2 从点的位置往后截取  获得图片的后缀
                            String suffix = originalFilename.substring(index);

                    //1.3 给图片随机生成新名字
                            String newFileName = UUID.randomUUID().toString()+suffix;

            //2. 调用图片上传工具 上传图片
                    QiniuUtil.upload(imgFile.getBytes(),newFileName);

           //3. 把所有上传的图片放到     第一个集合中   不点击保存的
                    jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFileName);

            //4. 返回图片名称  用于图片回显
                    return Result.success("上传成功",newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }


}
